﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using MiniFox.Components;
using MiniFox.Web;

namespace MiniFox.Platform.OAuth2.Web.Filters
{
    /// <summary>
    /// 
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public sealed class PassportFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="actionExecutingContext"></param>
        public override void OnActionExecuting(ActionExecutingContext actionExecutingContext)
        {
            var httpContext = actionExecutingContext.HttpContext;
            var request = httpContext.Request;
            string authTicket = null;
            
            if (request.Cookies.Keys.Contains(PassportToken.OPEN_AUTH_TICKET)) //从cookie取票
            {
                authTicket = request.Cookies[PassportToken.OPEN_AUTH_TICKET];
            }

            if (string.IsNullOrWhiteSpace(authTicket) && request.Headers.Keys.Contains(PassportToken.OPEN_AUTH_TICKET)) //从http头取票
            {
                authTicket = request.Headers[PassportToken.OPEN_AUTH_TICKET];
            }

            var stateManagement = ComponentFactory.GetComponent<IAuthenticationStateManagement>();
            stateManagement.AuthTicketID = authTicket;
            stateManagement.ClientInfomation.ClientIP = request.GetClientIP();
            stateManagement.ClientInfomation.UserAgent = request.Headers.UserAgent;

            httpContext.Items[AuthorizationStateManagement.AUTH_STATE_CONTEXT] = stateManagement;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
        {
            var httpContext = actionExecutedContext.HttpContext;
            var statemanagement = httpContext.Items[AuthorizationStateManagement.AUTH_STATE_CONTEXT] as IAuthenticationStateManagement;

            var response = httpContext.Response;
            var authTicket = statemanagement.AuthTicketID;


            //清除cookie值
            response.Cookies.Delete(PassportToken.OPEN_AUTH_TICKET, new CookieOptions
            {
                Expires = DateTimeOffset.UtcNow.AddDays(-1)
            });
            //回写状态，滑动过期
            if (!string.IsNullOrEmpty(authTicket))
            {
                if (response.Headers.Keys.Contains(PassportToken.OPEN_AUTH_TICKET))
                {
                    response.Headers[PassportToken.OPEN_AUTH_TICKET] = authTicket;
                }
                else
                {
                    response.Headers.Append(PassportToken.OPEN_AUTH_TICKET, authTicket);
                }

                var cookieStateExpiration = DateTimeOffset.UtcNow.AddSeconds(statemanagement.CookieStateExpires);
                
                response.Cookies.Append(PassportToken.OPEN_AUTH_TICKET, authTicket, new CookieOptions
                {
                    Expires = cookieStateExpiration
                });
            }
        }
    }
}
